package com.jhgsys.internal.dict.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.dict.entity.Dict;
import com.jhgsys.internal.dict.entity.DictItem;
import com.jhgsys.internal.dict.mapper.DictMapper;
import com.jhgsys.internal.dict.service.IDictItemService;
import com.jhgsys.internal.dict.service.IDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务字典 Service实现
 *
 * @author chenweihua
 * @date 2020-05-22 15:28:25
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService {

    @Autowired
    private IDictItemService dictItemService;

    /**
     * 查询（分页）
     *
     * @param request QueryRequest
     * @param dict    dict
     * @return IPage<Dict>
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    public IPage<Dict> findDicts(QueryRequest request, Dict dict) {
        Page<Dict> page = new Page<>(request.getPageNum(), request.getPageSize());
        return this.baseMapper.selectDictPage(page, dict);
    }

    /**
     * 查询（所有）
     *
     * @param dict dict
     * @return List<Dict>
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    public List<Dict> findDicts(Dict dict) {
        LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Dict::getDictId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return Dict
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    public Dict findDictById(String id) {
        Dict d = this.baseMapper.selectById(id);
        String code = d.getDictCode();
        List<DictItem> items = dictItemService.list(
                new LambdaQueryWrapper<DictItem>().eq(DictItem::getDictCode, code).orderByAsc(DictItem::getSortNum)
        );
        d.setDictItems(items);
        return d;
    }

    /**
     * 新增
     *
     * @param dict dict
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createDict(Dict dict) {
        List<Dict> d = this.list(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getDictCode, dict.getDictCode())
                .or()
                .eq(Dict::getDictName, dict.getDictName()));
        if (!d.isEmpty()) {
            throw new RuntimeException("字典编码或字典名称重复！");
        }
        this.save(dict);
        dictItemService.saveDictItemBatch(dict.getDictItems());
    }

    /**
     * 修改
     *
     * @param dict dict
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    @Transactional
    public void updateDict(Dict dict) {
        this.saveOrUpdate(dict);
        dictItemService.deleteByDictCode(dict.getDictCode());
        dictItemService.saveDictItemBatch(dict.getDictItems());
    }

    /**
     * 逻辑删除
     *
     * @param dict    dict
     * @param dictIds dictIds
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    @Transactional
    public void deleteDict(Dict dict, String dictIds) {
        List<String> list = Arrays.asList(dictIds.split(StringPool.COMMA));
        List<Dict> dicts = this.list(new LambdaQueryWrapper<Dict>().in(Dict::getDictId, list));
        this.baseMapper.delete(new LambdaQueryWrapper<Dict>().in(Dict::getDictId, list));
        dictItemService.getBaseMapper().delete(new LambdaQueryWrapper<DictItem>().in(DictItem::getDictCode, dicts.stream().map(Dict::getDictCode).collect(Collectors.toList())));
    }

    /**
     * 物理删除
     *
     * @param dictIds dictIds
     * @author chenweihua
     * @date 2020-05-22 15:28:25
     */
    @Override
    @Transactional
    public void physicallyDeleteDict(String dictIds) {
        List<String> list = Arrays.asList(dictIds.split(StringPool.COMMA));
        LambdaQueryWrapper<Dict> wapper = new LambdaQueryWrapper<>();
        wapper.in(Dict::getDictId, list);
        this.remove(wapper);
    }

    /**
     * 获取有效字典
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<DictItem> findDictByCode(String dictCode) {
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getDictCode, dictCode);
        queryWrapper.eq(DictItem::getItemStatus, '1');
        queryWrapper.apply(" EXISTS (SELECT dict_code FROM basic_dict WHERE dict_code='" + dictCode + "' AND STATUS = '1') ");
        return dictItemService.list(queryWrapper);
    }

    @Override
    public String findDictLabel(String dictCode, String itemCode) {
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DictItem::getDictCode, dictCode);
        queryWrapper.eq(DictItem::getItemCode, itemCode);
        queryWrapper.eq(DictItem::getItemStatus, '1');
        queryWrapper.last("limit 1");
        DictItem item = dictItemService.getOne(queryWrapper);
        return item != null ? item.getItemName() : "";
    }

    @Override
    public Map<String, String> findDictMapByCode(String dictCode) {
        Map<String, String> reMap = new HashMap<>();
        List<DictItem> data = findDictByCode(dictCode);

        if (CollUtil.isNotEmpty(data)) {
            reMap = data.stream().collect(Collectors.toMap(DictItem::getItemCode, DictItem::getItemName, (k1, k2) -> k1));
        }


        return reMap;
    }

    /**
     * 根据item_code获取有效字典
     *
     * @param itemCodes
     * @return
     */
    @Override
    public List<DictItem> findDictByItemCodes(String dictCode, List<String> itemCodes) {
        LambdaQueryWrapper<DictItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DictItem::getItemCode, itemCodes);
        queryWrapper.eq(DictItem::getDictCode, dictCode);
        queryWrapper.eq(DictItem::getItemStatus, '1');
        queryWrapper.apply(" EXISTS (SELECT dict_code FROM basic_dict WHERE dict_code='" + dictCode + "' AND STATUS = '1') ");
        return dictItemService.list(queryWrapper);
    }
}
